import { Inject, Injectable, InternalServerErrorException } from '@nestjs/common';
import { PROJECT_REPO_TOKEN } from '../../const';
import { Repository } from 'typeorm';
import { ProjectEntity } from './project.entity';
import { CreateProjectDto } from './dto/create-project.dto';
import { async } from 'rxjs/internal/scheduler/async';

@Injectable()
export class ProjectService {

  constructor(
    @Inject(PROJECT_REPO_TOKEN)
    private readonly projectRepo: Repository<ProjectEntity>,
  ) {
  }

  findAll(name: string): Promise<ProjectEntity[]> | Promise<[ProjectEntity[], number]> {
    if (name) {
      return this.projectRepo.findAndCount({
        where: {
          name,
        },
      });
    } else {
      return this.projectRepo.find();
    }

  }

  create(createProjectDto: CreateProjectDto) {
    // const project = this.projectRepo.create({ ...createProjectDto });
    // return this.projectRepo.save(project);
    return this.projectRepo
      .createQueryBuilder('project')
      .insert()
      .into('project')
      .values({ ...createProjectDto })
      .execute();
  }

  findOneById(id: number) {
    return this.projectRepo.findOne(id);
  }

  deleteOne(id: number) {
    return this.projectRepo.delete(id);
  }

  async deleteAll() {
    try {
      return await this.projectRepo.find({ select: ['id'] })
        .then(() => [{ id: 1 }, { id: 2 }, { id: 3 }])
        .then(projects => {
          return Promise.all(projects.map(async ({ id }) => {
            const p = await this.projectRepo.findOne(id);
            return this.projectRepo.remove(p);
          }));
        });
    } catch (e) {
      throw new InternalServerErrorException(e.message);
    }
  }

}
